// 白屏检测和修复工具
export class WhiteScreenDetector {
  constructor() {
    this.isDetecting = false
    this.detectionTimer = null
    this.retryCount = 0
    this.maxRetries = 3
    this.detectionDelay = 2000 // 2秒后开始检测
    this.retryDelay = 1000 // 重试间隔
  }

  // 开始检测白屏
  startDetection() {
    if (this.isDetecting) return
    
    this.isDetecting = true
    console.log('🔍 开始白屏检测...')
    
    this.detectionTimer = setTimeout(() => {
      this.detectWhiteScreen()
    }, this.detectionDelay)
  }

  // 停止检测
  stopDetection() {
    this.isDetecting = false
    if (this.detectionTimer) {
      clearTimeout(this.detectionTimer)
      this.detectionTimer = null
    }
  }

  // 检测白屏
  detectWhiteScreen() {
    try {
      const isWhiteScreen = this.checkForWhiteScreen()
      
      if (isWhiteScreen) {
        console.warn('⚠️ 检测到白屏，尝试修复...')
        this.handleWhiteScreen()
      } else {
        console.log('✅ 页面正常渲染')
        this.stopDetection()
      }
    } catch (error) {
      console.error('白屏检测出错:', error)
    }
  }

  // 检查是否为白屏
  checkForWhiteScreen() {
    // 方法1: 检查DOM元素数量
    const bodyChildren = document.body.children.length
    const hasContent = bodyChildren > 1 // 至少有app容器和其他内容
    
    // 方法2: 检查是否有可见的内容元素
    const visibleElements = document.querySelectorAll('*:not(script):not(style):not(meta):not(link)')
    const hasVisibleContent = Array.from(visibleElements).some(el => {
      const rect = el.getBoundingClientRect()
      return rect.width > 0 && rect.height > 0 && 
             window.getComputedStyle(el).visibility !== 'hidden' &&
             window.getComputedStyle(el).display !== 'none'
    })

    // 方法3: 检查Vue应用是否挂载
    const appElement = document.getElementById('app')
    const hasVueContent = appElement && appElement.children.length > 0

    // 方法4: 检查是否有路由视图内容
    const routerView = document.querySelector('[data-v-router-view]') || 
                      document.querySelector('.router-view') ||
                      document.querySelector('router-view')
    const hasRouterContent = routerView && routerView.children.length > 0

    console.log('白屏检测结果:', {
      bodyChildren,
      hasContent,
      hasVisibleContent,
      hasVueContent,
      hasRouterContent
    })

    // 如果所有检查都失败，则认为是白屏
    return !hasContent || !hasVisibleContent || !hasVueContent
  }

  // 处理白屏
  handleWhiteScreen() {
    this.retryCount++
    
    if (this.retryCount > this.maxRetries) {
      console.error('❌ 白屏修复失败，已达到最大重试次数')
      this.showFallbackUI()
      return
    }

    console.log(`🔄 第 ${this.retryCount} 次尝试修复白屏...`)

    // 尝试不同的修复策略
    switch (this.retryCount) {
      case 1:
        this.fixStrategy1() // 强制重新渲染
        break
      case 2:
        this.fixStrategy2() // 重新挂载Vue应用
        break
      case 3:
        this.fixStrategy3() // 重新加载页面
        break
    }

    // 延迟后再次检测
    setTimeout(() => {
      if (this.isDetecting) {
        this.detectWhiteScreen()
      }
    }, this.retryDelay)
  }

  // 修复策略1: 强制重新渲染
  fixStrategy1() {
    try {
      console.log('🔧 策略1: 强制重新渲染')
      
      // 触发窗口resize事件
      window.dispatchEvent(new Event('resize'))
      
      // 尝试重新触发Vue的响应式更新
      const appElement = document.getElementById('app')
      if (appElement) {
        appElement.style.display = 'none'
        setTimeout(() => {
          appElement.style.display = ''
        }, 100)
      }
    } catch (error) {
      console.error('策略1失败:', error)
    }
  }

  // 修复策略2: 重新挂载Vue应用
  fixStrategy2() {
    try {
      console.log('🔧 策略2: 重新挂载Vue应用')
      
      // 如果有全局的Vue应用实例，尝试重新挂载
      if (window.__VUE_APP__) {
        const app = window.__VUE_APP__
        app.unmount()
        setTimeout(() => {
          app.mount('#app')
        }, 100)
      }
    } catch (error) {
      console.error('策略2失败:', error)
    }
  }

  // 修复策略3: 重新加载页面
  fixStrategy3() {
    console.log('🔧 策略3: 重新加载页面')
    window.location.reload()
  }

  // 显示备用UI
  showFallbackUI() {
    const appElement = document.getElementById('app')
    if (appElement) {
      appElement.innerHTML = `
        <div style="
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100vh;
          background: #f5f5f5;
          font-family: Arial, sans-serif;
        ">
          <div style="
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 400px;
          ">
            <h2 style="color: #e74c3c; margin-bottom: 20px;">⚠️ 页面加载异常</h2>
            <p style="color: #666; margin-bottom: 20px;">
              页面出现了渲染问题，请尝试以下解决方案：
            </p>
            <div style="margin-bottom: 20px;">
              <button onclick="window.location.reload()" style="
                background: #3498db;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 4px;
                cursor: pointer;
                margin: 5px;
              ">刷新页面</button>
              <button onclick="window.location.href='/'" style="
                background: #27ae60;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 4px;
                cursor: pointer;
                margin: 5px;
              ">返回首页</button>
            </div>
            <p style="font-size: 12px; color: #999;">
              如果问题持续存在，请联系技术支持
            </p>
          </div>
        </div>
      `
    }
  }
}

// 创建全局实例
export const whiteScreenDetector = new WhiteScreenDetector()

// 自动启动检测（在页面加载完成后）
if (typeof window !== 'undefined') {
  window.addEventListener('load', () => {
    setTimeout(() => {
      whiteScreenDetector.startDetection()
    }, 1000)
  })
  
  // 在路由变化时重新检测
  window.addEventListener('popstate', () => {
    setTimeout(() => {
      whiteScreenDetector.startDetection()
    }, 500)
  })
}
